package base.网络编程.UDP.聊天;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class 客户端二 {
    static volatile String otherIp = null;
    static DatagramSocket ds;
    static byte[] bytes;

    static {
        try {
            ds = new DatagramSocket();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        Rr t1 = new Rr();
        t1.setDaemon(true);
        t1.start();


        getIp();
        //DatagramSocket ds = new DatagramSocket();//空参：随机端口发送

        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("---输入：");
            String str = sc.nextLine();
            if ("110".equals(str)){
                break;
            }
            //String str = "你好世界！！";
            bytes = str.getBytes();
            InetAddress ip = InetAddress.getByName(otherIp);
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length,ip,11111);

            ds.send(dp);
        }
    }

    private static void getIp() throws IOException {
        String s1 = "我要连接你";
        bytes = s1.getBytes();
        InetAddress ip = InetAddress.getByName("255.255.255.255");
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length,ip,11111);
        ds.send(dp);
    }
}

class Rr extends Thread{
    @Override
    public void run() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(10086);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);

        while (true) {
            //解析数据包
            try {
                ds.receive(dp);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            byte[] data = dp.getData();
            int len = dp.getLength();
            InetAddress ip = dp.getAddress();
            String host = ip.getHostName();
            int port = dp.getPort();

            Pattern p = Pattern.compile("(\\d+\\.){3}\\d+");
            Matcher m = p.matcher(String.valueOf(ip));
            String matIp = null;
            if (m.find()){
                matIp = m.group();
            }
            客户端二.otherIp = String.valueOf(matIp);
            System.out.println("接收到来自"+ip+"的消息："+new String(data,0,len));
            System.out.println("对方端口号为："+port+",总共"+len+"个字节");


        }
    }
}